from flask import Blueprint, request, jsonify, session, render_template
from config import db
from models.models import GoodsType
from utils.utils import result

goods_type_service = Blueprint('good_type_service', __name__)


@goods_type_service.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


# 添加商品种类
@goods_type_service.route('/goods/type/add', methods=['POST'])
def goods_type_add():
    name = request.form["name"]
    _type = GoodsType(name=name)
    try:
        db.session.add(_type)
        db.session.commit()
    except:
        return result(400, "已存在该商品类别，添加失败！")
    return result(200, "添加商品类别成功！")


# 删除商品种类
@goods_type_service.route("/goods/type/delete", methods=["DELETE"])
def goods_type_delete():
    name = request.form["name"]
    ok = GoodsType.query.filter_by(name=name).delete()
    db.session.commit()
    if ok == 0:
        return result(400, "没有找到该商品类别，删除失败！")
    else:
        return result(200, "删除商品类别成功！")


# # 商品分类查询
# @goods_type_service.route("/goods/type")
# def goods_type():
#     types = GoodsType.query.all()
#     data = []
#     for _type in types:
#         value = {
#             'id': _type.id,
#             'name': _type.name,
#             'num': _type.num
#         }
#         data.append(value)
#     return jsonify({'code': 0, 'count': len(data), "msg": "", 'data': data})


# 商品分类查询
@goods_type_service.route("/goods/type")
def goods_type():
    page = int(request.args.get("curr", 1))  # 当前页码，默认为1
    per_page = int(request.args.get("nums", 10))  # 每页记录数，默认为10

    types = GoodsType.query.paginate(page=page, per_page=per_page)
    data = []
    for _type in types.items:
        value = {
            'id': _type.id,
            'name': _type.name,
            'num': _type.num
        }
        data.append(value)
    return jsonify({
        'code': 0,
        'count': types.total,
        'msg': '',
        'data': data
    })
